from django.http import HttpResponse
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from utils.exceptions import BaseException
from rest_framework.pagination import PageNumberPagination


# 分页器
class PageNumber(PageNumberPagination):
    page_size = 20                  # 每页显示多少条
    page_size_query_param = 'size'  # URL中每页显示条数的参数
    page_query_param = 'page'       # URL中页码的参数
    max_page_size = None            # 最大页码数限制


class BaseAPIView(APIView):
    serializer_classes = None

    def get(self, request, *args, **kwargs):
        pass

    def post(self, request, *args, **kwargs):
        pass

    def get_serializer_data(self, many=False):
        serializer = self.serializer_classes(data=self.request.GET, many=many)
        serializer.is_valid(raise_exception=True)
        return serializer.validated_data

    def post_serializer_data(self, many=False):
        serializer = self.serializer_classes(data=self.request.data, many=many)
        serializer.is_valid(raise_exception=True)
        return serializer.validated_data

    def serializer_out(self, out_data, many=False):
        serializer = self.serializer_classes(out_data, many=many)
        return serializer.data

    def pagination_with_serializer(self, queryset):
        pagination_obj = PageNumber()
        pagination_result = pagination_obj.paginate_queryset(queryset, request=self.request, view=self)
        serializer = self.serializer_classes(pagination_result, many=True)
        return pagination_obj.get_paginated_response({'data': serializer.data})

    def succeed(self, message='请求成功', data=None):
        return Response({
            'status_code': 200,
            'message': message,
            'data': data
        }, status=status.HTTP_200_OK)

    def error(self, message='请求失败'):
        raise BaseException(detail=message)

    def image_response(self, img):
        # response = HttpResponse(content_type='image/jpg')
        # img.save(response, 'JPEG')
        # response['Content-Disposition'] = 'attachment; filename="piece.jpg"'
        # return response

        return HttpResponse(img, content_type='image/jpg')

